'use client'

import { useState, useEffect, useMemo, useCallback } from 'react'
import DashboardLayout from '@/components/layouts/DashboardLayout'
import AddSceneModal from '@/components/scenes/AddSceneModal'
import SceneCard from '@/components/scenes/SceneCard'
import { Scene, SceneGroup, SceneTag, SceneFilter } from '@/types/scene'
import { toast } from 'react-hot-toast'
import SceneImportExport from '@/components/scenes/SceneImportExport'
import SceneGroupManager from '@/components/scenes/SceneGroupManager'
import SceneSearch from '@/components/scenes/SceneSearch'
import { message } from 'antd'
import { Download, Upload, Plus } from 'lucide-react'

type SortField = 'name' | 'createdAt' | 'status' | 'conditionCount' | 'actionCount'
type SortOrder = 'asc' | 'desc'

interface SortConfig {
  field: SortField
  order: SortOrder
}

export default function ScenesPage() {
  const [scenes, setScenes] = useState<Scene[]>([])
  const [devices, setDevices] = useState<any[]>([])
  const [isAddModalOpen, setIsAddModalOpen] = useState(false)
  const [editingScene, setEditingScene] = useState<Scene | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [selectedScenes, setSelectedScenes] = useState<Set<string>>(new Set())
  const [sortConfig, setSortConfig] = useState<SortConfig>({
    field: 'createdAt',
    order: 'desc'
  })
  const [groups, setGroups] = useState<SceneGroup[]>([])
  const [selectedGroupId, setSelectedGroupId] = useState<string>()
  const [tags, setTags] = useState<SceneTag[]>([])
  const [filter, setFilter] = useState<SceneFilter>({
    search: '',
    tags: [],
    status: 'all',
    dateRange: {}
  })
  const [selectedScene, setSelectedScene] = useState<Scene | null>(null)
  const [showAddModal, setShowAddModal] = useState(false)
  const [showImportModal, setShowImportModal] = useState(false)

  useEffect(() => {
    Promise.all([
      fetchScenes(),
      fetchGroups(),
      fetchTags(),
      fetchDevices()
    ]).finally(() => {
      setLoading(false)
    })
  }, [])

  const fetchScenes = async () => {
    try {
      setLoading(true)
      const response = await fetch('/api/scenes', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      const data = await response.json()
      
      // 确保 data 是数组
      if (Array.isArray(data)) {
        console.log('Fetched scenes with devices:', data)
        setScenes(data)
      } else {
        // 如果不是数组，设置为空数组
        console.error('Scenes data is not an array:', data)
        setScenes([])
      }
    } catch (error) {
      console.error('获取场景列表失败:', error)
      message.error('获取场景列表失败')
      setScenes([]) // 错误时设置为空数组
    } finally {
      setLoading(false)
    }
  }

  const fetchGroups = async () => {
    try {
      const res = await fetch('/api/scene-groups')
      if (!res.ok) throw new Error('获取分组列表失败')
      const data = await res.json()
      setGroups(data)
    } catch (error) {
      console.error('获取分组列表失败:', error)
    }
  }

  const fetchTags = async () => {
    try {
      const res = await fetch('/api/scene-tags')
      const data = await res.json()
      
      if (data.error) {
        throw new Error(data.error)
      }
      
      setTags(data)
    } catch (error) {
      console.error('获取标签列表失败:', error)
      message.error('获取标签列表失败')
    }
  }

  const fetchDevices = async () => {
    try {
      const res = await fetch('/api/devices')
      if (!res.ok) throw new Error('获取设备列表失败')
      const data = await res.json()
      setDevices(data)
    } catch (error) {
      console.error('获取设备列表失败:', error)
      message.error('获取设备列表失败')
    }
  }

  const handleAddScene = async (sceneData: any) => {
    try {
      const response = await fetch('/api/scenes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sceneData),
      })

      if (!response.ok) {
        throw new Error('创建场景失败')
      }

      // 刷新场景列表
      fetchScenes()
      toast.success('创建场景成功')
    } catch (error) {
      toast.error('创建场景失败')
    }
  }

  const handleToggleScene = async (id: string) => {
    try {
      const scene = scenes.find(s => s.id === id)
      if (!scene) return

      const res = await fetch(`/api/scenes/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          isActive: !scene.isActive
        }),
      })

      if (!res.ok) throw new Error('更新场景状态失败')
      
      setScenes(prev =>
        prev.map(scene =>
          scene.id === id
            ? { ...scene, isActive: !scene.isActive }
            : scene
        )
      )
    } catch (error) {
      console.error('切换场景状态失败:', error)
    }
  }

  const handleDeleteScene = async (id: string) => {
    try {
      await fetch(`/api/scenes/${id}`, {
        method: 'DELETE'
      })
      // 刷新场景列表
      fetchScenes()
      message.success('场景删除成功')
    } catch (error) {
      message.error('场景删除失败')
    }
  }

  const handleEditScene = (scene: Scene) => {
    setSelectedScene(scene)
    setShowAddModal(true)
  }

  const handleExecuteScene = async (id: string) => {
    try {
      await fetch(`/api/scenes/${id}/execute`, {
        method: 'POST'
      })
      message.success('场景执行成功')
    } catch (error) {
      message.error('场景执行失败')
    }
  }

  const handleDuplicateScene = async (scene: Scene) => {
    try {
      const newSceneData = {
        name: `${scene.name} (副本)`,
        isActive: true,
        conditions: scene.conditions,
        actions: scene.actions,
      }

      const res = await fetch('/api/scenes', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newSceneData),
      })

      if (!res.ok) throw new Error('复制场景失败')
      const newScene = await res.json()
      setScenes(prev => [...prev, newScene])
      toast.success('场景复制成功')
    } catch (error) {
      console.error('复制场景失败:', error)
      toast.error('复制场景失败')
    }
  }

  const handleSelectScene = (id: string) => {
    setSelectedScenes(prev => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }

  const handleSelectAll = () => {
    if (selectedScenes.size === scenes.length) {
      setSelectedScenes(new Set())
    } else {
      setSelectedScenes(new Set(scenes.map(scene => scene.id)))
    }
  }

  const handleBatchToggle = async (active: boolean) => {
    try {
      const results = await Promise.all(
        Array.from(selectedScenes).map(id =>
          fetch(`/api/scenes/${id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ isActive: active }),
          })
        )
      )

      const allSuccess = results.every(res => res.ok)
      if (allSuccess) {
        setScenes(prev =>
          prev.map(scene =>
            selectedScenes.has(scene.id)
              ? { ...scene, isActive: active }
              : scene
          )
        )
        toast.success(`已${active ? '启用' : '禁用'}所选场景`)
      } else {
        toast.error('批量操作部分失败')
      }
    } catch (error) {
      console.error('批量操作失败:', error)
      toast.error('批量操作失败')
    }
  }

  const handleBatchDelete = async () => {
    if (!confirm('确定要删除所选场景吗？此操作不可撤销。')) {
      return
    }

    try {
      const results = await Promise.all(
        Array.from(selectedScenes).map(id =>
          fetch(`/api/scenes/${id}`, {
            method: 'DELETE',
          })
        )
      )

      const allSuccess = results.every(res => res.ok)
      if (allSuccess) {
        setScenes(prev =>
          prev.filter(scene => !selectedScenes.has(scene.id))
        )
        setSelectedScenes(new Set())
        toast.success('已删除所选场景')
      } else {
        toast.error('批量删除部分失败')
      }
    } catch (error) {
      console.error('批量删除失败:', error)
      toast.error('批量删除失败')
    }
  }

  const handleBatchExport = async () => {
    try {
      const selectedIds = Array.from(selectedScenes)
      if (selectedIds.length === 0) {
        toast.error('请先选择要导出的场景')
        return
      }

      const res = await fetch('/api/scenes/export/batch', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ sceneIds: selectedIds }),
      })

      if (!res.ok) throw new Error('导出失败')

      const blob = await res.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `scenes_batch_${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      toast.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      toast.error('导出失败')
    }
  }

  const handleBatchDuplicate = async () => {
    try {
      const selectedIds = Array.from(selectedScenes)
      if (selectedIds.length === 0) {
        toast.error('请先选择要复制的场景')
        return
      }

      // 获取选中的场景数据
      const selectedSceneData = scenes
        .filter(scene => selectedScenes.has(scene.id))
        .map(scene => ({
          name: `${scene.name} (副本)`,
          isActive: true,
          conditions: scene.conditions,
          actions: scene.actions,
        }))

      // 批量创建场景
      const results = await Promise.all(
        selectedSceneData.map(sceneData =>
          fetch('/api/scenes', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(sceneData),
          })
        )
      )

      // 获取新创建的场景数据
      const newScenes = await Promise.all(
        results.map(res => res.json())
      )

      const allSuccess = results.every(res => res.ok)
      if (allSuccess) {
        setScenes(prev => [...prev, ...newScenes])
        setSelectedScenes(new Set())
        toast.success(`已复制 ${selectedIds.length} 个场景`)
      } else {
        toast.error('批量复制部分失败')
      }
    } catch (error) {
      console.error('批量复制失败:', error)
      toast.error('批量复制失败')
    }
  }

  const handleBatchExecute = async () => {
    try {
      const selectedIds = Array.from(selectedScenes)
      if (selectedIds.length === 0) {
        toast.error('请先选择要执行的场景')
        return
      }

      // 批量执行场景
      const results = await Promise.all(
        selectedIds.map(id =>
          fetch(`/api/scenes/${id}/execute`, {
            method: 'POST',
          })
        )
      )

      const allSuccess = results.every(res => res.ok)
      if (allSuccess) {
        toast.success(`已执行 ${selectedIds.length} 个场景`)
      } else {
        toast.error('批量执行部分失败')
      }

    } catch (error) {
      console.error('批量执行失败:', error)
      toast.error('批量执行失败')
    }
  }

  // 首先定义排序函数
  const sortScenes = useCallback((scenes: Scene[]) => {
    if (!Array.isArray(scenes)) {
      console.error('Scenes is not an array:', scenes)
      return []
    }
    
    return [...scenes].sort((a, b) => {
      switch (sortConfig.field) {
        case 'name':
          return sortConfig.order === 'asc' 
            ? a.name.localeCompare(b.name)
            : b.name.localeCompare(a.name)
        
        case 'createdAt':
          return sortConfig.order === 'asc'
            ? new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
            : new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
        
        case 'status':
          return sortConfig.order === 'asc'
            ? Number(a.isActive) - Number(b.isActive)
            : Number(b.isActive) - Number(a.isActive)
        
        case 'conditionCount':
          return sortConfig.order === 'asc'
            ? a.conditions.length - b.conditions.length
            : b.conditions.length - a.conditions.length
        
        case 'actionCount':
          return sortConfig.order === 'asc'
            ? a.actions.length - b.actions.length
            : b.actions.length - a.actions.length
        
        default:
          return 0
      }
    })
  }, [sortConfig])

  // 然后使用 useMemo 过滤和排序场景
  const filteredScenes = useMemo(() => {
    let filtered = scenes

    // 分组过滤
    if (selectedGroupId) {
      filtered = filtered.filter(scene => 
        selectedGroupId === 'ungrouped' 
          ? !scene.groupId
          : scene.groupId === selectedGroupId
      )
    }

    // 搜索和标签过滤
    if (filter.search || filter.tags.length > 0 || filter.status !== 'all' || 
        (filter.dateRange.start || filter.dateRange.end)) {
      filtered = filtered.filter(scene => {
        // 搜索过滤
        if (filter.search && !scene.name.toLowerCase().includes(filter.search.toLowerCase())) {
          return false
        }

        // 标签过滤
        if (filter.tags.length > 0 && !filter.tags.every(tagId => 
          scene.tags.some(tag => tag.id === tagId)
        )) {
          return false
        }

        // 状态过滤
        if (filter.status !== 'all' && 
            ((filter.status === 'active' && !scene.isActive) || 
             (filter.status === 'inactive' && scene.isActive))) {
          return false
        }

        // 日期范围过滤
        if (filter.dateRange.start || filter.dateRange.end) {
          const sceneDate = new Date(scene.createdAt)
          if (filter.dateRange.start && sceneDate < filter.dateRange.start) {
            return false
          }
          if (filter.dateRange.end && sceneDate > filter.dateRange.end) {
            return false
          }
        }

        return true
      })
    }

    // 排序
    return sortScenes(filtered)
  }, [scenes, selectedGroupId, filter, sortConfig, sortScenes])

  // 切换排序
  const handleSort = (field: SortField) => {
    setSortConfig(prev => ({
      field,
      order: prev.field === field && prev.order === 'asc' ? 'desc' : 'asc'
    }))
  }

  // 渲染排序图标
  const renderSortIcon = (field: SortField) => {
    if (sortConfig.field !== field) {
      return <span className="text-white/40">↕</span>
    }
    return <span className="text-primary-400">{sortConfig.order === 'asc' ? '↑' : '↓'}</span>
  }

  // 修改场景分组
  const handleMoveToGroup = async (sceneIds: string[], groupId?: string) => {
    try {
      const results = await Promise.all(
        sceneIds.map(id =>
          fetch(`/api/scenes/${id}`, {
            method: 'PUT',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ groupId }),
          })
        )
      )

      const allSuccess = results.every(res => res.ok)
      if (allSuccess) {
        fetchScenes()
        toast.success('移动场景成功')
      } else {
        toast.error('移动场景部分失败')
      }
    } catch (error) {
      console.error('移动场景失败:', error)
      toast.error('移动场景失败')
    }
  }

  // 导出场景数据
  const handleExport = () => {
    // 检查是否有场景数据
    if (!scenes || scenes.length === 0) {
      toast.error('没有可导出的场景数据')
      return
    }

    try {
      // 准备导出数据
      const exportData = scenes.map(scene => ({
        name: scene.name,
        groupId: scene.groupId,
        group: scene.group?.name,
        conditions: scene.conditions,
        actions: scene.actions,
        isActive: scene.isActive
      }))

      // 创建 Blob 对象
      const blob = new Blob([JSON.stringify(exportData, null, 2)], { 
        type: 'application/json' 
      })
      
      // 创建下载链接
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `场景配置_${new Date().toLocaleDateString()}.json`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      
      // 清理
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      toast.success('场景数据导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      toast.error('场景数据导出失败')
    }
  }

  if (loading) {
    return (
      <DashboardLayout>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500"></div>
        </div>
      </DashboardLayout>
    )
  }

  if (error) {
    return (
      <DashboardLayout>
        <div className="flex items-center justify-center h-64">
          <div className="text-red-400">{error}</div>
        </div>
      </DashboardLayout>
    )
  }

  return (
    <DashboardLayout>
      <div className="flex">
        {/* 左侧分组列表 */}
        <div className="w-64 pr-6">
          <SceneGroupManager
            groups={groups}
            selectedGroupId={selectedGroupId}
            onSelectGroup={setSelectedGroupId}
            onGroupsChange={fetchGroups}
          />
        </div>

        {/* 右侧场景列表 */}
        <div className="flex-1">
          <div className="space-y-6">
            {/* 顶部操作栏 */}
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-4">
                {/* 只保留一个导出按钮 */}
                <button
                  onClick={handleExport}
                  disabled={!scenes || (scenes.length === 0 && selectedScenes.size === 0)}
                  className={`px-4 py-2 rounded-lg flex items-center space-x-2 
                    ${(!scenes || (scenes.length === 0 && selectedScenes.size === 0))
                      ? 'bg-gray-600 cursor-not-allowed' 
                      : 'bg-blue-600 hover:bg-blue-700'}`}
                >
                  <Download className="w-4 h-4" />
                  <span>导出场景{selectedScenes.size > 0 ? `(${selectedScenes.size})` : ''}</span>
                </button>

                <button
                  onClick={() => setShowImportModal(true)}
                  className="px-4 py-2 bg-green-600 hover:bg-green-700 rounded-lg flex items-center space-x-2"
                >
                  <Upload className="w-4 h-4" />
                  <span>导入场景</span>
                </button>

                <button
                  onClick={() => setShowAddModal(true)}
                  className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center space-x-2"
                >
                  <Plus className="w-4 h-4" />
                  <span>添加场景</span>
                </button>
              </div>
            </div>

            {/* 搜索和过滤 */}
            <SceneSearch
              onFilterChange={setFilter}
              tags={tags}
            />

            {scenes.length > 0 && (
              <div className="card bg-background-paper/30 backdrop-blur-lg border border-white/10 rounded-lg p-4">
                <div className="flex items-center space-x-4 mb-4">
                  {[
                    { field: 'name', label: '名称' },
                    { field: 'createdAt', label: '创建时间' },
                    { field: 'status', label: '状态' },
                    { field: 'conditionCount', label: '条件数' },
                    { field: 'actionCount', label: '动作数' }
                  ].map(({ field, label }) => (
                    <button
                      key={field}
                      onClick={() => handleSort(field as SortField)}
                      className={`flex items-center space-x-1 text-sm transition-colors
                        ${sortConfig.field === field 
                          ? 'text-primary-400' 
                          : 'text-white/60 hover:text-white/80'}`}
                    >
                      <span>{label}</span>
                      {renderSortIcon(field as SortField)}
                    </button>
                  ))}
                </div>

                <div className="flex items-center space-x-4">
                  <label className="flex items-center space-x-2">
                    <input
                      type="checkbox"
                      checked={selectedScenes.size === scenes.length}
                      onChange={handleSelectAll}
                      className="h-4 w-4 rounded border-white/20 bg-white/5 checked:bg-primary-500 checked:border-0 transition-colors"
                    />
                    <span className="text-sm text-white/70">全选</span>
                  </label>

                  {selectedScenes.size > 0 && (
                    <div className="flex items-center space-x-3 ml-6">
                      <span className="text-sm text-white/60">
                        已选择 {selectedScenes.size} 个场景
                      </span>
                      <BatchActionButton onClick={() => handleBatchToggle(true)}>
                        批量启用
                      </BatchActionButton>
                      <BatchActionButton onClick={() => handleBatchToggle(false)}>
                        批量禁用
                      </BatchActionButton>
                      <button
                        onClick={handleBatchDelete}
                        className="px-3 py-1 text-sm bg-primary-500/20 text-primary-300 rounded-md hover:bg-primary-500/30"
                      >
                        批量删除
                      </button>
                      <button
                        onClick={handleBatchExport}
                        className="px-3 py-1 text-sm bg-primary-500/20 text-primary-300 rounded-md hover:bg-primary-500/30"
                      >
                        批量导出
                      </button>
                      <button
                        onClick={handleBatchDuplicate}
                        className="px-3 py-1 text-sm bg-primary-500/20 text-primary-300 rounded-md hover:bg-primary-500/30"
                      >
                        批量复制
                      </button>
                      <button
                        onClick={handleBatchExecute}
                        className="px-3 py-1 text-sm bg-primary-500/20 text-primary-300 rounded-md hover:bg-primary-500/30"
                      >
                        批量执行
                      </button>
                      <select
                        onChange={(e) => handleMoveToGroup(Array.from(selectedScenes), e.target.value || undefined)}
                        className="text-sm bg-white/5 border border-white/10 rounded-lg text-white/70 
                                  px-3 py-1.5 hover:bg-white/10 transition-colors
                                  focus:outline-none focus:ring-1 focus:ring-primary-500"
                      >
                        <option value="">移动到分组...</option>
                        <option value="">未分组</option>
                        {groups.map(group => (
                          <option key={group.id} value={group.id} className="bg-background-paper">
                            {group.name}
                          </option>
                        ))}
                      </select>
                    </div>
                  )}
                </div>
              </div>
            )}

            {scenes.length === 0 ? (
              <div className="text-center py-12">
                <p className="text-white/60">暂无场景</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredScenes.map(scene => (
                  <SceneCard
                    key={scene.id}
                    scene={scene}
                    onExecute={handleExecuteScene}
                    onDelete={handleDeleteScene}
                    onEdit={handleEditScene}
                  />
                ))}
              </div>
            )}

            <SceneImportExport 
              isOpen={showImportModal}
              onClose={() => setShowImportModal(false)}
              onSuccess={() => {
                fetchScenes() // 导入成功后刷新场景列表
                setShowImportModal(false)
              }}
            />

            <AddSceneModal
              open={isAddModalOpen || showAddModal}
              scene={selectedScene}
              onClose={() => {
                setIsAddModalOpen(false)
                setShowAddModal(false)
                setSelectedScene(null)
              }}
              onSuccess={() => {
                fetchScenes()
                setIsAddModalOpen(false)
                setShowAddModal(false)
                setSelectedScene(null)
              }}
            />
          </div>
        </div>
      </div>
    </DashboardLayout>
  )
}

const BatchActionButton = ({ onClick, children }: { onClick: () => void, children: React.ReactNode }) => (
  <button
    onClick={onClick}
    className="px-3 py-1.5 text-sm bg-white/5 text-white/70 rounded-lg 
             hover:bg-white/10 hover:text-white/90 transition-colors"
  >
    {children}
  </button>
) 